var isExit=true;

/**
 * 添加映射规则
 */
function DataMappingRuleAdd(){
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	var checkReturn = $('#inputForm').checkForm(null, false);
	if(checkReturn){
		$.ajax({
			   type: "GET",
			   dataType:"html",
			   cache: false,
			   url: _ctx + "/data_mapping/data_mapping_rule_add.do",
			   data: {srcDsId:$("#srcDsId").val()},
			   beforeSend : function(){
		       },
			   success: function(content){
					$('#dataMappingRuleAddDiv').html(content);
					var hiddenByClick = false;
					window.parent.iframeModal("dataMappingRuleAddModal", $('#dataMappingRuleAddModal').html(), hiddenByClick);
					window.parent.iframeModal("dataMappingRuleAddModal", $('#dataMappingRuleAddModal').html(), hiddenByClick);
			   },
			   error:function(){
				   parent.ui.msg( '请求发送失败！',0 );
			   }
		});
	}
}
var realTimeData = "";

/**
 * 实时预览
 */
function realTimePreview(){
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	var checkReturn = $('#inputForm').checkForm(null, false);
	if(checkReturn){
		sbmMappingRuleInfo();
		$.ajax({
		   type: "POST",
		   dataType:"json",
		   cache: false,
		   url: _ctx + "/data_mapping/data_mapping_realtime_preview.do",
		   data: {
			   srcDsId:$("#srcDsId").val(),
			   funcMappingList:JSON.stringify(mappingRuleList)
		   },
		   beforeSend : function(){
				$("#realTimePreviewBtn").html("处理中...").attr("disabled", "disabled");
	       },
		   success: function(resp){
			   if (resp.status == 1) {
				   realTimeData = resp.data;
				   parseRealTimeData();
				   $("#sbmDiv").css("display","");
				   parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度
				   parent.ui.msg(resp.msg, 1);
			   }else{
				   parent.ui.msg(resp.msg, 0);
			   }
			   $("#realTimePreviewBtn").html("实时预览").removeClass("disabled").attr("disabled", null);
		   },
		   error:function(){
			   parent.ui.msg( '请求发送失败！',0 );
			   $("#realTimePreviewBtn").html("实时预览").removeClass("disabled").attr("disabled", null);
		   }
		});
	}
}

/**
 * 提交
 */
function submitBtn(){
	sbmMappingRuleInfo();
	
	$(function() {
		$('#inputForm input').tooltip();
		$('#inputForm').checkForm();
		$('#inputForm').ajaxForm({
			url : _ctx + "/data_mapping/add_data_mapping.do",
			type : "POST",
			dataType : "json",
			beforeSubmit : function() {
				$("#sbmBtn").html("处理中...")
						.attr("disabled", "disabled");
			},
			data: {
				funcMappingList:JSON.stringify(mappingRuleList)
			},
			success : function(resp) {
				if (resp.status == '1') {
					isExit = false;
					parent.ui.msg(resp.msg, 1);
					ui.go(_ctx + '/data_mapping/data_mapping_list.do');
				} else {
					parent.ui.msg(resp.msg, 0);
				}
				$("#sbmBtn").html("提交").removeClass("disabled").attr("disabled", null);
			},
			error : function(resp) {
				parent.ui.msg('请求发送失败', 0);
				$("#sbmBtn").html("提交").removeClass("disabled").attr("disabled", null);
			}
		});
	});
} 

function deleteFxMapping(val){
	var id = $(val.parentElement.parentElement.parentElement).attr("id")
	parent.ui.confirm('确认删除映射规则?',function(){
		removeRule(val); 
		$('#inputForm input').tooltip();
		$('#inputForm').checkForm();
		var checkReturn = $('#inputForm').checkForm(null, false);
		var mappingType = $('input[name="mappingType"]:checked').val();
		if(mappingType == '1'){
			if(checkReturn){
				sbmMappingRuleInfo();
				$.ajax({
				   type: "POST",
				   dataType:"json",
				   cache: false,
				   url: _ctx + "/data_mapping/data_mapping_realtime_preview.do",
				   data: {
					   srcDsId:$("#srcDsId").val(),
					   funcMappingList:JSON.stringify(mappingRuleList)
				   },
				   beforeSend : function(){
			       },
				   success: function(resp){
					   if (resp.status == 1) {
						   $("#lable_info_data").addClass("label-primary");//设置进度条
						   realTimeData = resp.data;
						   parseRealTimeData();
						   $("#sbmDiv").css("display","");
						   parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度					 
					   }
				   },
				   error:function(){
					  
				   }
				});
			}
		}
	});	
}

/**
 * 移除映射规则
 */
function removeRule(val){
	//设置每行的序号
	var currentTr = $(val.parentElement.parentElement.parentElement.parentElement).find("tr");
	var trLength = currentTr.length;
	var currentNum = val.parentElement.parentElement.parentElement.firstElementChild.textContent;
	currentNum = Number(currentNum);
	for(var i=currentNum+1; i<=trLength; i++){
		var next = currentTr[i-1];
		next.firstElementChild.textContent = i-1;
	}	
	$(val.parentElement.parentElement.parentElement).remove();//移除当前行
}

var mappingRuleList = new Array();
/**
 *映射规则数据
 */
function sbmMappingRuleInfo(){
	mappingRuleList = new Array();
	var mappingId = $("#mappingId").val();
	if(mappingId == "" || mappingId == null || mappingId == "undefined"){
		mappingId = getUuid();
	}
	$("#mappingId").val(mappingId);
	var trIndex = 0;
	var tableInfo = $("#mappingRuleList table tbody tr");
	var trLength = tableInfo.length;
	for(var i=0; i<trLength; i++){
		var trInfo = tableInfo[i];
		var id = trInfo.getAttribute("id");
		if(id == "" || id == null || id == "undefined"){
			id = getUuid();
		}
		var tableName = trInfo.getAttribute("tableName");
		var actObj = trInfo.getAttribute("actObj");
		var fxId = trInfo.getAttribute("fxId");
		var argContent = trInfo.getAttribute("argContent");
		var fxActOnType = trInfo.getAttribute("fxActOnType");
		var vo = '{"id":"'+id+'","mappingId":"'+mappingId+'","tableName":"'+tableName+'","actObj":"'+actObj+'","fxId":"'+fxId+'","argContent":'+argContent+',"fxActOnType":"'+fxActOnType+'","fxExecOrder":""}';
		mappingRuleList[trIndex] = vo;
		trIndex += 1;
	}
}

/**
 *生成UUID
 */
function getUuid(){
	var len=32;//32长度
	var radix=16;//16进制
	var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid=[],i;radix=radix||chars.length;if(len){for(i=0;i<len;i++)uuid[i]=chars[0|Math.random()*radix];}else{var r;uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[14]='4';for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r];}}}
    return uuid.join('');
} 

/**
 * 解析实时预览数据
 */
function parseRealTimeData(){
	$("#realTimePreview").css("display","");
	var i=0;
	var selectOption = "";
	var originHtml = "";
	var afterHtml = "";
	$.each(realTimeData, function(key, val) {
		if(i==0){
			changeMappingTable(key);
		}
		selectOption += '<option tableIndex="'+(i+1)+'">'+eval("realTimeData."+key).originTable.tableName+'</option>';
		
		i++;
	});
	$("#mappingTableIndex").html("1/"+Object.keys(realTimeData).length);
	$("#mappingSelectObject").html(selectOption);
	
}

function changeMappingTable(tableName){
	var topH = $(parent.document).scrollTop();
	$("#befMapTab table tbody").remove();
	$("#afterMapTab table tbody").remove();
	var tableInfo = eval("realTimeData."+tableName);
	var ifIsomorphism = tableInfo.ifIsomorphism//是否同构
	var originTable = tableInfo.originTable;
	var originTabCol = originTable.tabColMap;
	var mappingAfterTable = tableInfo.mappingAfterTable;
	var mappingAfterTabCol = "";
	if(mappingAfterTable != null){
		mappingAfterTabCol = mappingAfterTable.tabColMap;
	}
	var originHtml = "";
	var afterHtml = "";
	if(ifIsomorphism == 1){//同构
		$("#ifIsomorphismFont span b").html("同构");
		$("#ifIsomorphismFont").removeClass("label-danger").addClass("label-success");
		originHtml += '<tbody>';
		var col = 1;
		$.each(originTabCol, function(key1, val1) {
			originHtml += ' <tr>'
			            + '  <td>'+col+'</td>'
			            + '  <td>'+val1.colName+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colComment+'">'+substrF(val1.colComment)+'</span></td>'
			            + '  <td>'+val1.colType+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colDefault+'">'+substrF(val1.colDefault)+'</span></td>'
			            + ' </tr>';
			col += 1;            
		});
		originHtml += '</tbody>';
		afterHtml = originHtml; 
		$("#mappingBeforeTabName").html(originTable.tableName);
		$("#mappingAfterTabName").html(originTable.tableName);
	}else{
		$("#ifIsomorphismFont span b").html("异构");
		$("#ifIsomorphismFont").removeClass("label-success").addClass("label-danger");
		//原表结构
		originHtml += '<tbody>';
		var col1 = 1;
		$.each(originTabCol, function(key1, val1) {
			originHtml += ' <tr>'
			            + '  <td>'+col1+'</td>'
			            + '  <td>'+val1.colName+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colComment+'">'+substrF(val1.colComment)+'</span></td>'
			            + '  <td>'+val1.colType+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colDefault+'">'+substrF(val1.colDefault)+'</span></td>'
			            + ' </tr>';
			col1 += 1;            
		});
		originHtml += '</tbody>';
		
		if(mappingAfterTabCol == "" || mappingAfterTabCol == undefined || mappingAfterTabCol == null){//排除表
			afterHtml = "";
			$("#mappingBeforeTabName").html(originTable.tableName);
			$("#mappingAfterTabName").html(null);
		}else{

			//映射后表结构
			afterHtml += '<tbody>';
			var col2 = 1;
			$.each(mappingAfterTabCol, function(key1, val1) {
				if(val1 != ""){
					var colType = "";
					var colDefault = "";
					if(val1.colType != null && val1.colType != "" && val1.colType != undefined){
						colType = val1.colType;
					}
					if(val1.colDefault != null && val1.colDefault != "" && val1.colDefault != undefined){
						colDefault = val1.colDefault;
					}
					afterHtml += ' <tr>'
			            + '  <td>'+col2+'</td>'
			            + '  <td>'+val1.colName+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colComment+'">'+substrF(val1.colComment)+'</span></td>'
			            + '  <td>'+colType+'</td>'
			            + '  <td><span class="tipMe" title="'+val1.colDefault+'">'+substrF(val1.colDefault)+'</span></td>'
			            + ' </tr>';
					col2 += 1;     
				}
			});
			afterHtml += '</tbody>';
			$("#mappingBeforeTabName").html(originTable.tableName);
			$("#mappingAfterTabName").html(mappingAfterTable.tableName);
		}
	}
	$("#mappingTableIndex").html($("#mappingSelectObject").find("option:selected").attr("tableIndex")+"/"+Object.keys(realTimeData).length);
	$("#befMapTab table thead").after(originHtml);
	$("#afterMapTab table thead").after(afterHtml);
	changeTableHeight();
	parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度
	$('.tipMe').tooltip({'placement':'top'});
	$(parent.document).scrollTop(topH);//滚动条定位
}

function changeTableHeight(){
	var tabHeight = $("#befMapTab").css("height");
	var imgHeight = Number(tabHeight.replace("px","")) / 2 - 28;
	imgHeight = imgHeight + "px";
	$("#arrowID").css("margin-top",imgHeight);
}

var lastSelectOption = "";
function changeSrcDs(){
	var srcDsId = $("#srcDsId").val();
	$("#destDsId").prop("selectedIndex", 0);
	if(lastSelectOption != ""){
		lastSelectOption.css("display", "");;
	}
	if(srcDsId != ""){
		lastSelectOption = $("#destDsId option[value="+srcDsId+"]");
		$("#destDsId option[value="+srcDsId+"]").css("display", "none");
	}
}

function substrF(str){
	var strs = "";
	if(str != null && str != "" && str != "undefined"){
		if(str.length>7){
			strs = str.substring(0,7)+"...";
		}else{
			strs = str;
		}
	}
	return strs;
}

function changeMpTypeRadio(){
	var mpType = $('input[name="mappingType"]:checked').val();
	var srcDsOptionV = "";
	var destDsOptionV = "";
	if(mpType == '1'){
		$(document.getElementById("mappingRuleList")).find("table tbody tr").remove();
		$("#realTimePreviewBtn").css("display","");
		//设置源端数据源、目的端数据源下拉列表
		srcDsOptionV = $("#srcDsId").find("option");
		changeDsSelOption(srcDsOptionV, "srcDsId", "1");
		destDsOptionV = $("#destDsId").find("option");
		changeDsSelOption(destDsOptionV, "destDsId", "1");
	}
	if(mpType == '3'){
		$(document.getElementById("mappingRuleList")).find("table tbody tr").remove();
		$("#realTimePreviewBtn").css("display","none");
		//设置源端数据源、目的端数据源下拉列表
		srcDsOptionV = $("#srcDsId").find("option");
		changeDsSelOption(srcDsOptionV, "srcDsId", "2");
		destDsOptionV = $("#destDsId").find("option");
		changeDsSelOption(destDsOptionV, "destDsId", "2");
		
	}
}

function changeDsSelOption(optionV, dsId, dsTypeStr){
	$("#"+dsId).prop("selectedIndex", 0);
	for(var i=0;i<optionV.length;i++){
		var dsType = $(optionV[i]).attr("dstype");
		if(dsType != "" && dsType != "undefined" && dsType != null){
			if(dsType == dsTypeStr){
				$($("#"+dsId).find("option")[i]).css("display","");
			}else{
				$($("#"+dsId).find("option")[i]).css("display","none");
			}
		}
	}
}
